package com.fulihui.usercore.service;

import com.fulihui.usercore.api.UserTagService;
import com.fulihui.usercore.biz.shard.UserManager;
import com.fulihui.usercore.common.util.Errors;
import com.fulihui.usercore.condition.TagCondition;
import com.fulihui.usercore.core.repository.UserRepository;
import com.fulihui.usercore.core.repository.UserTagRespitory;
import com.fulihui.usercore.dto.TagDTO;
import com.fulihui.usercore.dto.UserDTO;
import com.fulihui.usercore.enums.CommonStateEnum;
import com.fulihui.usercore.request.tag.MarkUserRequest;
import com.fulihui.usercore.request.tag.TagSaveRequest;
import org.apache.dubbo.config.annotation.Service;
import org.near.servicesupport.error.CommonServiceErrorEnum;
import org.near.servicesupport.error.InvokeServiceException;
import org.near.servicesupport.request.TRequest;
import org.near.servicesupport.result.BaseResult;
import org.near.servicesupport.result.ResultBuilder;
import org.near.servicesupport.result.TMultiResult;
import org.near.servicesupport.result.TSingleResult;
import org.near.servicesupport.util.ServiceAssert;
import org.near.toolkit.common.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Willard.Hu on 2016/5/17.
 */
@Service(version = "1.0.0")
public class UserTagServiceImpl implements UserTagService {
    private final transient Logger LOG = LoggerFactory.getLogger(UserTagServiceImpl.class);
    @Autowired
    private UserTagRespitory userTagRespitory;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserManager userManager;

    @Override
    public BaseResult save(TagSaveRequest request) {
        TagDTO tagDTO = new TagDTO();
        if (StringUtil.isBlank(request.getId())) { // insert
            tagDTO.setTagName(request.getTagName());
            tagDTO.setState(CommonStateEnum.ON);
            userTagRespitory.create(tagDTO);
        } else { // update
            tagDTO.setId(request.getId());
            tagDTO.setTagName(request.getTagName());
            boolean b = userTagRespitory.update(tagDTO);
            if (!b) {
                throw new InvokeServiceException(Errors.UserTags.TAG_SAVE_FAILED);
            }
        }
        return ResultBuilder.succ(BaseResult.class);
    }

    @Override
    public BaseResult markUser(MarkUserRequest request) {
        UserDTO userDTO = new UserDTO();
        userDTO.setUserId(request.getUserId());
        userDTO.setTagIds(request.getIds());
        boolean b = userRepository.modify(userDTO);
        if (!b) {
            LOG.error("用户{}更新标签失败", request.getUserId());
            throw new InvokeServiceException(Errors.User.USER_MODIFY_FAILED);
        }
        return ResultBuilder.succ(BaseResult.class);
    }

    /**
     * 删除数据后，用户获取标签会处理同步，将删除的标签从用户标签中去掉
     */
    @Override
    public BaseResult delete(TRequest<String> request) {
        ServiceAssert.notBlank(request.getCondition(),
                CommonServiceErrorEnum.REQUEST_PARAMETER_ERROR);
        boolean b = userTagRespitory.delete(request.getCondition());
        if (!b) {
            throw new InvokeServiceException(Errors.UserTags.TAG_DELETE_FAILED);
        }
        return ResultBuilder.succ(BaseResult.class);
    }

    @Override
    public TSingleResult<TagDTO> queryByPK(TRequest<String> request) {
        ServiceAssert.notBlank(request.getCondition(),
                CommonServiceErrorEnum.REQUEST_PARAMETER_ERROR);
        TagDTO tagDTO = userTagRespitory.queryByPK(request.getCondition());
        return ResultBuilder.succTSingle(tagDTO);
    }

    @Override
    public TMultiResult<TagDTO> query(TRequest<TagCondition> request) {
        TagCondition condition = request.getCondition();
        ServiceAssert.notNull(condition, CommonServiceErrorEnum.REQUEST_PARAMETER_ERROR);
        List<TagDTO> tags = null;
        if (StringUtil.isNotBlank(condition.getUserId())) {
            // TODO 以后用户标签需要了再修改
            /*UserDTO userDTO = userRepository.queryByPK(condition.getUserId());
            if (userDTO != null) {
                tags = userTagRespitory.queryByPKs(userDTO.getTagIds());
                userDTO.setTagList(tags);
                if (tags == null || tags.size() != userDTO.getTagIds().size()) { // 有变动，重置用户标签
                    userManager.resetTags(userDTO.getUserId(), tags);
                }
            }*/
        } else {
            tags = userTagRespitory.queryAll();
        }
        if (CollectionUtils.isEmpty(tags)) {
            tags = Collections.emptyList();
        } else {
            if (StringUtil.isNotBlank(condition.getTagName())) {
                tags = tags.stream()
                        .filter((it) -> condition.getTagName().contains(it.getTagName()))
                        .collect(Collectors.toList());
            }
        }
        return ResultBuilder.succTMulti(tags);
    }
}
